//
//  StatusPictureView.swift
//  Weibo8023
//
//  Created by styshy on 15/12/12.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit
import SDWebImage

private let statusPictureMargin:CGFloat = 8
// 可重用标示符
private let StatusPictureCellId = "StatusPictureCellId"

class StatusPictureView: UICollectionView{

    // 微博视图模型
    var viewModel:StatusViewModel?{
        didSet{
            
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }

    
    // 设置布局
    init(){
        
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = statusPictureMargin
        layout.minimumLineSpacing = statusPictureMargin
        
//        layout.itemSize = CGSize(width: 300, height: 150)
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        dataSource = self
        delegate = self
        
        // 注册重用item
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
        
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

// MARK: - 转场动画实现
extension StatusPictureView:PhotoBrowserPresentDelegate{
    // 参与专场动画的图像视图
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        print("专场代理，获取图片")
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
//        iv.clipsToBounds = true
        let key = viewModel?.thumbnailUrls![indexPath.item].absoluteString
        iv.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        iv.sizeToFit()
        
        return iv
    }
    
    func photoBrowserFromRect(indexPath: NSIndexPath) -> CGRect {
        print("专场动画起始位置")
        guard let cell = self.cellForItemAtIndexPath(indexPath) else{
            return CGRectZero
        }
        
        // 转换位置坐标
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return rect
    }
    
    func photoBrowserToRect(indexPath: NSIndexPath) -> CGRect {
        print("转场动画结束位置")
        let key = viewModel?.thumbnailUrls![indexPath.item].absoluteString
        
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else{
            return CGRectZero
        }
        
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        var y:CGFloat = 0
        
        let screenHeight = UIScreen.mainScreen().bounds.size.height
        
        if h < screenHeight {
            y = (screenHeight - h) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
        
    }
}

// MARK: - 代理方法
extension StatusPictureView:UICollectionViewDelegate{
    // 监听选择了那个cell
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let userInfo = [WBStatusSelectedIndexPathNotification: indexPath,
            WBStatusSelectedPhotoURLsKey: viewModel!.thumbnailUrls!]
        
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification, object: self, userInfo: userInfo)
    }
}
                                            

// MARK: - 数据源方法
extension StatusPictureView:UICollectionViewDataSource{
    
    /// item的个数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imgUrl = viewModel?.thumbnailUrls![indexPath.row]
        
        return cell
        
    }
}




// MARK: - 计算视图大小
extension StatusPictureView {
    
    /// 计算视图大小
    private func calcViewSize() -> CGSize {
        
        // 1. 准备
        // 每行的照片数量
        let rowCount: CGFloat = 3
        // 最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * statusPictureMargin) / rowCount
        
        // 2. 设置 layout 的 itemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth-1, height: itemWidth-1)
        
        // 3. 获取图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        // 计算开始
        // 1> 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 2> 一张图片
        if count == 1 {
            var size = CGSize(width: 150, height: 120)
            
            // 利用 SDWebImage 检查本地的缓存图像 - key 就是 url 的完整字符串
            // 问：SDWebImage 是如何设置缓存图片的文件名 完整 URL 字符串 -> `MD5`
            if let key = viewModel?.thumbnailUrls?.first?.absoluteString {
                
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                if image != nil{
                    size = image.size
                }
            }
            
            // 过窄处理 - 针对长图
            size.width = size.width < 40 ? 40 : size.width
            // 过宽的图片
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * w / size.width
                
                size = CGSize(width: w, height: h)
            }
            
            // 内部图片的大小
            layout.itemSize = size
            
            // 配图视图的大小
            return size
        }
        
        // 3> 四张图片 2 * 2 的大小
        if count == 4 {
            let w = 2 * itemWidth + statusPictureMargin
            
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他图片 按照九宫格来显示
        // 计算出行数
        /**
        2 3
        5 6
        7 8 9
        */
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * statusPictureMargin
        let w = rowCount * itemWidth + (rowCount - 1) * statusPictureMargin
        
        return CGSize(width: w, height: h)
    }
}




/// 设置每个item中的内容
class StatusPictureViewCell:UICollectionViewCell {
    
    var imgUrl:NSURL?{
        didSet{
            imgView.sd_setImageWithURL(imgUrl, placeholderImage: nil, options: [.RetryFailed,.RefreshCached])
            
            gifLabel.hidden =  (imgUrl?.absoluteString  ?? "" as NSString).pathExtension.lowercaseString != "gif"
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(imgView)
        contentView.addSubview(gifLabel)
        
        // 设置自动布局
        imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        gifLabel.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(imgView.snp_right)
            make.bottom.equalTo(imgView.snp_bottom)
        }
    }
    
    // 设置图片的填充模式
    private lazy var imgView:UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
        
    }()
    
    // timeline_image_gif
    private lazy var gifLabel:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
}

